import Vue from 'vue'
import Vuex from 'vuex'
import {
	login,
	logout,
	getInfo
} from "@/api/modules/user.api.js"
import config from '@/config'
import storage from '@/utils/storage'

import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'

const state = {
	//所有参数需要前后对应
	token: getToken(),
	permissions: storage.get("permissions") || [],
	roles: storage.get("roles") || [],
	userInfo: storage.get("userInfo") || {},
	userId: storage.get("userId") || '',
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USERINFO: (state, data) => {
		state.userInfo = data
		storage.set('userInfo', data)
	},
	update(state, [key, value]) {
		state[key] = value;
		uni.setStorageSync(key, value)
	},
}

const actions = {
	// 登录
	Login({
		commit,
		dispatch
	}, userInfo) {
		return new Promise((resolve, reject) => {
			login(userInfo.form)
				.then(res => {
					if (res.code == 200) {
						commit('update', ['TOKEN', res.data.token])
						commit('update', ['userId', res.data.userId])
						dispatch('GetInfo', userInfo.path)
					}
					resolve(res)
				})
				.catch(error => {
					reject(error)
				})
		})
	},
	// 获取用户信息
	GetInfo({
		commit,
		state
	}, path) {
		return new Promise((resolve, reject) => {
			getInfo(state.userId)
				.then(res => {
					if (res.code == 200) {
						let user = res.data
						user.avatar = config.imgUrl + user.avatar
						if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
							commit('update', ['roles', res.roles])
							commit('update', ['permissions', res.permissions])
						} else {
							commit('update', ['roles', 'ROLE_DEFAULT'])
						}
						commit('update', ["userInfo", user])
						storage.set('userInfo', user)
						uni.showToast({
							title: '登录成功',
							icon: 'none',
							success() {
								uni.router.to({
									path: path,
									params: user
								})
							}
						})
					}
					resolve(res)
				})
				.catch(error => {
					reject(error)
				})
		})
	},
	// 退出系统
	LogOut({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			logout(state.token)
				.then(() => {
					uni.clearStorageSync()
					resolve()
				})
				.catch(error => {
					reject(error)
				})
		})
	},
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}